// pages/order/order-underway/uploading/uploading.js
import {
  request,processForm
} from '../../../../network/client'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    product_num: 0,
    // imgIndex:0,
    // 发送数据
    allList: [{
      product_num: '',
      car_info: '',
      supplement_factory_id: '',
      order_code: '',
      fileList: [],
      image: ''
    }],
    // fileList:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orderId: options.orderId,
    })
    this._request()
  },
  // 获取吨数的接口
  async _request() {
    let data = {
      order_id: this.data.orderId,
    }
    const res = await request(data)
    console.log("res", res);
    this.setData({
      product_num: res.data.product_num
    })
  },
  // 增加单据
  addData() {
    this.data.allList.push({
      product_num: '',
      car_info: '',
      supplement_factory_id: '',
      order_code: '',
      fileList: [],
      image: ''
    })
    this.setData({
      allList: this.data.allList
    })
  },
  // 删除单据
  delData() {
    if (this.data.allList.length > 1) {
      this.data.allList.pop()
      this.setData({
        allList: this.data.allList
      })
    } else {
      wx.showToast({
        title: '暂无数据可删除',
        icon: 'none',
        duration: 800,
        mask: true
      });
    }
  },
  // 删除图片
  delete(e) {
    console.log("执行了删除");
    let allList = this.data.allList;
    let index = e.currentTarget.dataset.index;
    allList[index].fileList = [];
    allList[index].image = '';
    this.setData({
      allList
    })
  },
  afterRead(event) {
    console.log("event",event);
    // path: "http://tmp/VaJJ4aL2h3Enbb8d97c102bc04526dd7d0509ea4f497.png"
    // 临时图片地址
    const {
      file
    } = event.detail;
    let index = event.currentTarget.dataset.index;//图片组件索引
    let allList = this.data.allList;
    console.log("aliList",allList);
    // 在相应的allList数据中push进图片地址
    allList[index].fileList.push({
      url: file.path
    })
    // 更新allList的数据
    this.setData({
      allList
    })
    // 调用上传图片接口
    this.uploadImg(index)
  },
  
  uploadImg(i) {
    let allList = this.data.allList;
    // url:'http://master.gddzxcx.com/'+'mobileadmin/update_img',
    wx.uploadFile({
      url: 'http://master.gddzxcx.com/' + 'mobileadmin/update_img',
      filePath: allList[i].fileList[0].url,
      name: 'image',
      formData: {
        token: wx.getStorageSync('token'),
      },
      success: res => {
        // console.log("上传图片res",res);
        // 将返回的数据解析成JSON格式
        let result = JSON.parse(res.data)
        // console.log("解析成JSON",result);
        if (result.code === 200) {
          // 将图片地址写到allList中
          allList[i].image = result.data
        } else {
          wx.showToast({
            title: '上传图片失败，请重新上传',
            icon: 'none',
            duration: 1500,
            mask: true
          });
        }
        this.setData({
          allList
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  // 输入触发的函数
  bindValue(e) {
    console.log("bindValue",e);
    let i = e.currentTarget.dataset.index; // 表单索引
    let allList = this.data.allList; // 列表信息集
    let value = e.currentTarget.dataset.value // 输入框名称
    let values = e.detail.value;  // 输入的值
    allList[i][value] = values; // 将输入的值添加到对应的数组中
    this.setData({
      allList: allList  // 更新列表信息集
    })
  },
  // 点击提交按钮
 async sumbit() {
    // 表单输入的信息
    let allList = this.data.allList;
    // 声明多个变量
    let sum = 0,
      product_num = [],
      car_info = [],
      supplement_factory_id = [],
      order_code = [],
      images = [],
      orderId = this.data.orderId;
    // map映射方法
    allList.map(item => {
      sum += Number(item.product_num);
      product_num.push(item.product_num);
      car_info.push(item.car_info);
      supplement_factory_id.push(item.supplement_factory_id);
      order_code.push(item.order_code);
      images.push(item.image);
    })
    if (+sum !== this.data.product_num) {
      wx.showToast({
        title: '所添加的商品数量不符合规范',
        icon: 'none',
        duration: 1500,
        mask: true
      });
    } else {
       let data={
          order_id: orderId,
          product_num: product_num.join(','),
          car_info: car_info.join(','),
          supplement_factory_id: supplement_factory_id.join(','),
          order_code: order_code.join(','),
          images: images.join(','),
          access_type: 'mobile'
        }
        const res=await processForm(data)
        console.log("res信息",res);
          if (res.code === 200) {
            wx.showToast({
              title: '添加数据成功',
              icon: 'none',
              duration: 1500,
              mask: true
            });
            wx.navigateBack({
              delta: 2
            })
          } else if (res.code === 500) {
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 1500,
              mask: true
            });
          } else {
            wx.showToast({
              title: '请填写完整的数据，再提交',
              icon: 'none',
              duration: 1500,
              mask: true
            });
          }
    }
  },
})